package com.mars.weixin.web.handler;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.mars.base.common.utils.SpringContextHolder;
import com.mars.base.common.utils.XmlUtils;
import com.mars.base.common.utils.date.DateUtils;
import com.mars.weixin.common.WeixinConstant;
import com.mars.weixin.model.msg.BaseMsg;
import com.mars.weixin.model.msg.TextMessage;
import com.mars.weixin.service.MsgService;
import com.mars.weixin.service.impl.MsgServiceImpl;


public class WeixinRequestHandler {

	private static Logger logger = LoggerFactory.getLogger(WeixinRequestHandler.class);

	public static String processRequest(HttpServletRequest request) {
		logger.debug("收到微信请求：" + DateUtils.getDateTime());
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "没有找到你想要的信息...";
			
			// xml请求解析
			Map<String, String> requestMap = XmlUtils.parseXml(request.getInputStream()) ;

			//将Map转换成对象
			BaseMsg baseMsg = JSON.parseObject(JSON.toJSONString(requestMap), BaseMsg.class) ;

			logger.debug("消息类型：" + baseMsg.getMsgType());
			logger.debug("消息内容：" + baseMsg.getContent());
			logger.debug("事件类型：" + baseMsg.getEvent());
			logger.debug("消息JSON：" + baseMsg);
			
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(baseMsg.getFromUserName());
			textMessage.setFromUserName(baseMsg.getToUserName());
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(WeixinConstant.RESP_MESSAGE_TYPE_TEXT);
			
			MsgService msgService = SpringContextHolder.getBean(MsgServiceImpl.class) ;
			
			// 文本消息
			if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_TEXT)) {
				Object textKeyWordHandler = msgService.textKeyWordHandler(baseMsg) ;
				if(null != textKeyWordHandler) {
					String beanToXml = XmlUtils.beanToXml(textKeyWordHandler) ;
					logger.debug("\r\n{}",beanToXml);
					return beanToXml ;
				}
			}
			// 图片消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！" ;
			}
			// 地理位置消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！坐标（X："+requestMap.get("Location_X")+"，Y："+requestMap.get("Location_Y")+"）地址：" + requestMap.get("Label") ;
			}
			// 链接消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
			}
			// 音频消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
			}
			// 事件推送
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_EVENT)) {
				// 自定义菜单点击事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_CLICK)) {
					Object clickEventHandler = msgService.clickEventHandler(baseMsg) ;
					if(null != clickEventHandler) {
						String beanToXml = XmlUtils.beanToXml(clickEventHandler) ;
						logger.debug("\r\n{}",beanToXml);
						return beanToXml ;
					}
				}
				
				// 扫码推事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_PUSH)) {
					respContent = "扫码推事件";
				}

				// 扫码推事件且弹出“消息接收中”
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_WAITMSG)) {
					respContent = "扫描后返回结果给用户";
				}

				// 订阅
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "感谢您的关注！";
				}
				// 取消订阅
				else if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
			}
			
			System.out.println("====================================回复内容===================================");
			textMessage.setContent(respContent);
			respMessage = XmlUtils.beanToXml(textMessage, "xml") ;
			logger.debug("\r\n{}",respMessage);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

}
